package com.insigma.business.qrcode.welfare.util;

import cn.hutool.crypto.digest.SM3;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Random;


public class PasswordUtils {

    private static String salt = "zhlbpwsign%^43";

    public PasswordUtils() {
    }

    public static String encode(String loginId, String password) {
        return DigestUtils.md5Hex(loginId + password);
    }

    public static Boolean checkPassword(String loginId, String password, String cipherText) {
        if (StringUtils.isBlank(cipherText)) {
            return false;
        }

        String encode = encode(loginId, password);
        if (encode.equals(cipherText)) {
            return true;
        }

        return false;
    }

    public static String generatePassword(int length) {
        String password = "";
        Random random = new Random();

        for (int i = 0; i < length; ++i) {
            int charOrNum = random.nextInt(2);
            if (charOrNum == 1) {
                int temp = random.nextInt(2) == 1 ? 65 : 97;
                password = password + (char) (random.nextInt(26) + temp);
            } else {
                password = password + random.nextInt(10);
            }
        }

        return password;
    }

    public static String encodeBySm3(String loginId, String password) {
        SM3 sm3 = new SM3(salt.getBytes());
        String s = sm3.digestHex(loginId + password);
        System.out.println(s);
        return s;
    }

    public static boolean adapterVerify(String loginId, String password, String realSign) {
        if (StringUtils.isBlank(realSign)) {
            return false;
        }

        if (realSign.length() > 40) {
            
            String encode = encodeBySm3(loginId, password);
            return encode.equals(realSign);
        } else {
            
            String encode = encode(loginId, password);
            return encode.equals(realSign);
        }
    }

}
